package com.loadmore.schedule

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.loadmore.common.App
import com.loadmore.common.base.BaseFragment
import com.loadmore.common.model.MessageEvent
import com.loadmore.common.model.Schedule
import com.loadmore.common.router.RouterPath
import com.loadmore.common.schedule.AlarmUtil
import com.loadmore.common.util.EventUtil
import com.loadmore.schedule.constants.ScheduleEventAction
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import kotlinx.android.synthetic.main.fragment_schedule_detail.*
import java.text.SimpleDateFormat
import java.util.*


@Route(path = RouterPath.ScheduleDetail)
class ScheduleDetailFragment:BaseFragment() {

    val start = 1
    val end = 2
    var remindScheduleType = 2
    var repeatSchedyleType = 0
    val repeatItems = arrayOf("一次性活动", "每分钟","每小时","每天", "每个工作日","每周","每月","每年")
    val remindItems = arrayOf("不提醒", "事件发生时", "提前10分钟","提前30分钟","提前一小时","提前一天")
    lateinit var dateFormat:SimpleDateFormat
    lateinit var timeFormat:SimpleDateFormat
    lateinit var startCalendar:Calendar
    lateinit var endCalendar: Calendar
    var schedule:Schedule?= null
    override fun getLayoutId(): Int {
        return R.layout.fragment_schedule_detail
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setMenu(R.menu.schedule_detail)
        startCalendar = Calendar.getInstance()
        endCalendar = Calendar.getInstance()
        dateFormat = SimpleDateFormat("yyyy/MM/dd E")
        timeFormat = SimpleDateFormat("HH:mm")
        val data = arguments?.getSerializable("data")
        if (data != null) {
            schedule = data as Schedule?
            startCalendar.timeInMillis = schedule!!.start_time
            endCalendar.timeInMillis = schedule!!.end_time
            remindScheduleType = schedule!!.remindType
            repeatSchedyleType = schedule!!.repeatType
            allDay.isChecked = schedule!!.allDay
            brief.setText(schedule!!.brief)
            location.setText(schedule!!.location)
            name.setText(schedule!!.name)
            remindType.text = remindItems[remindScheduleType]
            repeatType.text = repeatItems[repeatSchedyleType]
            delete.setOnClickListener {
                AlarmUtil.clearAlarm(context!!,schedule!!.id)
                App.daoSession.delete(schedule)
                EventUtil.post(MessageEvent(ScheduleEventAction.delete_schedule,schedule!!.id))
                finish()
            }
        }else{
            delete.visibility = View.GONE
            startCalendar.set(Calendar.MINUTE,0)
            startCalendar.add(Calendar.HOUR_OF_DAY,1)
            startCalendar.set(Calendar.MILLISECOND,0)
            endCalendar.timeInMillis = startCalendar.timeInMillis
            endCalendar.add(Calendar.HOUR_OF_DAY,1)
        }
        val date = Date(startCalendar.timeInMillis)
        start_day.text = dateFormat.format(date)
        start_time.text = timeFormat.format(date)



        val endDate = Date(endCalendar.timeInMillis)
        end_day.text = dateFormat.format(endDate)
        end_time.text = timeFormat.format(endDate)


        start_day.setOnClickListener {
            pickerDate(start)
        }

        start_time.setOnClickListener {
            pickerTime(start)
        }

        end_day.setOnClickListener {
            pickerDate(end)
        }
        end_time.setOnClickListener {
            pickerTime(end)
        }

        var mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog
        remindType.setOnClickListener {

            QMUIDialog.CheckableDialogBuilder(activity)
                    .setCheckedIndex(remindScheduleType)
                    .addItems(remindItems) { dialog, which ->
                        remindType.text = remindItems[which]
                        remindScheduleType = which
                        dialog.dismiss()
                    }
                    .create(mCurrentDialogStyle).show()
        }
        repeatType.setOnClickListener {


            QMUIDialog.CheckableDialogBuilder(activity)
                    .setCheckedIndex(repeatSchedyleType)
                    .addItems(repeatItems) { dialog, which ->
                        repeatType.text = repeatItems[which]
                        repeatSchedyleType = which
                        dialog.dismiss()
                    }
                    .create(mCurrentDialogStyle).show()
        }

    }

    override fun onMenuItemClick(menuItem: MenuItem) {
        super.onMenuItemClick(menuItem)
        when(menuItem.itemId) {
            R.id.create->{
                saveSchedule()

            }
        }
    }
    private fun saveSchedule() {
        val scheduleName = name.text.toString()
        val brief = brief.text.toString()
        val start_time = startCalendar.timeInMillis
        val end_time = endCalendar.timeInMillis
        val allDay = allDay.isChecked
        val location = location.text.toString()
        if (TextUtils.isEmpty(scheduleName)) {
            return
        }
//        if (startCalendar.timeInMillis -System.currentTimeMillis() <1000*60) {
//            Toast.makeText(context,"日程离开始时间很近了",Toast.LENGTH_SHORT).show()
//            return
//        }
        if (endCalendar.timeInMillis - startCalendar.timeInMillis < 1000*60) {
            Toast.makeText(context,"日程结束时间不能晚于开始时间",Toast.LENGTH_SHORT).show()
            return
        }

        if (schedule == null)
            schedule = Schedule()
        else
            AlarmUtil.clearAlarm(context!!,schedule?.id!!)
        schedule?.name = scheduleName
        schedule?.brief = brief
        schedule?.start_time = start_time
        schedule?.end_time = end_time
        schedule?.allDay = allDay
        schedule?.location = location
        schedule?.remindType = remindScheduleType
        schedule?.repeatType = repeatSchedyleType
        App.daoSession.insertOrReplace(schedule)
        AlarmUtil.setAlarm(context!!,schedule!!.id,start_time,end_time,remindScheduleType,repeatSchedyleType)

        EventUtil.post(MessageEvent(ScheduleEventAction.create_schedule,schedule!!.id))
        finish()
    }

    private fun pickerDate(type:Int) {
        val calendar:Calendar = if (type == start) startCalendar else endCalendar
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val dialog = DatePickerDialog(context, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->

            calendar.set(Calendar.YEAR,year)
            calendar.set(Calendar.MONTH,month)
            calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
            if(type == start) {
                start_day.text = dateFormat.format(Date(calendar.timeInMillis))
            }else{
                end_day.text = dateFormat.format(Date(calendar.timeInMillis))
            }


        },year,month,day)
        dialog.show()
    }
    private fun pickerTime(type:Int) {

        val calendar:Calendar = if (type == start) startCalendar else endCalendar
        val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val timePicker = TimePickerDialog(context, TimePickerDialog.OnTimeSetListener { timePicker, hourOfDay, minute ->
            calendar.set(Calendar.HOUR_OF_DAY,hourOfDay)
            calendar.set(Calendar.MINUTE,minute)
            calendar.set(Calendar.MILLISECOND,0)
            if(type == start) {
                start_time.text = timeFormat.format(Date(calendar.timeInMillis))
            }else{
                end_time.text = timeFormat.format(Date(calendar.timeInMillis))
            }
        },hourOfDay,minute,true)

        timePicker.show()
    }

}